<?php

namespace app\controller\merchant;

use app\BaseController;
use app\model\CouponBalanceNotice;
use app\model\CouponOrder;
use app\model\Store;
use app\model\Supplier;
use app\model\User;
use fuhai\Fuhai;
use think\helper\Str;
use think\response\Json;

class Coupon extends BaseController
{
    public function save(): Json
    {
        $account = $this->request->admin;
        $param = $this->request->post();

        //判断手机号是否存在
        $user = $this->app->make(User::class)->findOrRegister();
        if (empty($user)) throw new \Exception("用户信息获取失败！", 7001);
        if (empty($account['supplier_id'])) throw new \Exception("请先绑定供应商", 7001);
        $supplier = $this->app->make(Supplier::class)->where(['id' => $account['supplier_id']])->find();
        if (empty($supplier)) throw new \Exception("请先绑定供应商", 7001);
        //判断优惠券是否可用
        $fuhai = (new Fuhai($supplier['fuhai_appid'], $supplier['fuhai_appsecret']));
        $details = $fuhai->setApi("product/detail")->setData(['product_code' => $param['product_id']])->send();
        if (empty($details) || $details['code'] != 0) throw new \Exception($details['message'] ?? "接口请求异常", 7001);
        //判断门店余额是否充足
        $coupon_balance = $this->app->make(Store::class)->where(['id' => $account['store_id']])->find();
        $details = $details['data'];
        $balance = $coupon_balance['coupon_balance'] ? bcdiv($coupon_balance['coupon_balance'], 100, 2) : 0;
        if (empty($balance) || $balance < bcmul($details['cost'], $param['number'] ?? 1, 2)) throw new \Exception("门店余额不足！", 7001);
        $cost = bcmul($details['cost'], $param['number'] ?? 1, 2);
        //创建订单
        $order = [
            "order_sn" => date("YmdHis") . Str::random(6, 1),
            "number" => $param['number'] ?? 1,
            "uid" => $user['id'],
            "mobile" => $param['mobile'],
            "name" => $param['name'],
            "product_id" => $param['product_id'],
            "supplier_id" => $account['supplier_id'],
            "store_id" => $account['store_id'],
            "admin" => $account['id'],
            "state" => 0,
            "car" => $param['car'],
            "remark" => $param['remark'],
            "cost" => $cost,
            "face_value" => $details['coupon']['face_value'],
            "type" => $details['coupon']['type']
        ];
        $model = $this->app->make(CouponOrder::class);
        $model->save($order);
        $api = $param['type'] == 1 ? 'payment/create' : 'package/create';
        $sendData = $param['type'] == 1 ? [
            "mobile" => $param['mobile'],
            "number" => $param['number'] ?? 1,
            "out_order_sn" => $order['order_sn'],
            "product_code" => $order['product_id']
        ] : [
            "mobile" => $param['mobile'],
            "number" => $param['number'] ?? 1,
            "out_order_sn" => $order['order_sn'],
            "pack_id" => $order['product_id'],
        ];
        //下单
        $fuhaiCreate = $fuhai->setApi($api)->setData($sendData)->send();
        if (empty($fuhaiCreate) || $fuhaiCreate['code'] != 0) {
            $model->save(['state' => 2]);
            throw new \Exception($fuhaiCreate['message'] ?? "接口请求异常", 7001);
        }
        $payment = $fuhaiCreate['data'];
        $model->startTrans();
        $model->save([
            'state' => 1,
            'payment_sn' => $payment['order_sn'],
//            'payment_info' => json_encode($payment, 320)
        ]);
        $coupon_balance->dec("coupon_balance", bcmul($cost, 100))->save();
        $this->app->make(CouponBalanceNotice::class)->save([
            "content" => "向用户[{$order['mobile']}]发放优惠券成功,扣减金额[{$cost}]元！",
            "number" => bcmul($cost, 100),
            "type" => 2,
            "store_id" => $account['store_id'],
            "aid" => null,
            "uid" => $account['id'],
            "supplier_id" => $account['supplier_id']
        ]);
        $model->commit();
        return $this->success($model->toArray());
    }

    public function lst(): Json
    {
        return $this->success($this->app->make(CouponOrder::class)->pageData(1));
    }

    public function couponLst(): Json
    {
        //查看订单
        $order = $this->app->make(CouponOrder::class)->where('id', $this->request->get('id'))->find();
        if (empty($order)) throw new \Exception("订单不存在");
//        dd($order);
        $supplier = $this->app->make(Supplier::class)->where(['id' => $order['supplier_id']])->find();
        if (empty($supplier)) throw new \Exception("请先绑定供应商", 7001);
        $dat = $this->app->make(Fuhai::class, ['appid' => $supplier['fuhai_appid'], 'appsecret' => $supplier['fuhai_appsecret']])->setApi("payment/detail")->setData(['order_sn' => $order['payment_sn']])->send();
        if (empty($dat) || $dat['code'] != 0) throw new \Exception($dat['message'] ?? "接口请求异常", 7001);
        return $this->success($dat['data']);
    }

    public function refund(): Json
    {
        $account = $this->request->admin;
        //查看订单
        $order = $this->app->make(CouponOrder::class)->where('id', $this->request->post('id'))->find();
        if (empty($order)) throw new \Exception("订单不存在");
        $supplier = $this->app->make(Supplier::class)->where(['id' => $order['supplier_id']])->find();
        if (empty($supplier)) throw new \Exception("请先绑定供应商", 7001);
        $dat = $this->app->make(Fuhai::class, ['appid' => $supplier['fuhai_appid'], 'appsecret' => $supplier['fuhai_appsecret']])->setApi("payment/refund")->setData(['order_sn' => $order['order_sn']])->send();
        if (empty($dat) || $dat['code'] != 0) throw new \Exception($dat['message'] ?? "接口请求异常", 7001);
        $coupon_balance = $this->app->make(Store::class)->where(['id' => $account['store_id']])->find();
        $order->startTrans();
        $order->save(['state' => 4]);
        $cost = bcmul($order['cost'], 100);
        $coupon_balance->inc("coupon_balance", $cost)->save();
        $this->app->make(CouponBalanceNotice::class)->save([
            "content" => "向用户[{$order['mobile']}]退回优惠券成功,增加金额[{$order['cost']}]元！",
            "number" => bcmul($order['cost'], 100),
            "type" => 1,
            "store_id" => $account['store_id'],
            "aid" => null,
            "uid" => $account['id'],
            "supplier_id" => $account['supplier_id']
        ]);
        $order->commit();
        return $this->success($order);
    }
}